package com.demo.library.controller;

import com.demo.library.entity.Book;
import com.demo.library.service.BookService;
import com.demo.library.service.PublisherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    private BookService bookService;
    @Autowired
    private PublisherService publisherService;

    @GetMapping("/bookList")
    public ModelAndView bookList() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("bookList");
        modelAndView.addObject("books", bookService.findAll());
        modelAndView.addObject("publishers", publisherService.findAll());
        return modelAndView;
    }

    @GetMapping("/findById/{id}")
    public ModelAndView findById(@PathVariable Long id) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("book", bookService.findById(id));
        modelAndView.setViewName("BookEditor");
        modelAndView.addObject("publishers", publisherService.findAll());
        return modelAndView;
    }

    @PostMapping("/save")
    public String save(Book book, @RequestParam Integer publisherId) {
        book.setPublisher(publisherService.getById(publisherId));
        bookService.save(book);
        return "redirect:/book/bookList";
    }

    @GetMapping("/delete/{id}")
    public String deleteById(@PathVariable Long id) {
        bookService.deleteById(id);
        return "redirect:/book/bookList";
    }

    @PostMapping("/update")
    public String updateById(Book book, @RequestParam Integer publisherId) {
        book.setPublisher(publisherService.getById(publisherId));
        bookService.update(book);
        return "redirect:/book/bookList";
    }

    @GetMapping("/SearchList")
    public ModelAndView SearchList(@RequestParam String searchName) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("bookList");
        modelAndView.addObject("books", bookService.findByTitle(searchName));
        return modelAndView;
    }

    @GetMapping("/AuthorList")
    public ModelAndView AuthorList() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("authorList");
        modelAndView.addObject("authors", bookService.findAuthorList());
        return modelAndView;
    }
}